﻿Public Class Form1
    Public colTrades As New Collection
    Public colUnsavedTrades As New Stack(Of classTrades)
    Dim sortColumn As Integer = -1
    Public colSymbols As New Collection
    Public colSystems As New Collection

    Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
        If ListView1.Columns.Count > 0 Then
            Dim strSettings As String = ""
            For Each x As System.Windows.Forms.ColumnHeader In ListView1.Columns
                strSettings = x.Text & "=" & x.Width & "," & strSettings
            Next
            My.Settings.mnuCollumns_width = strSettings
        End If

        If Me.WindowState = FormWindowState.Maximized Then
            My.Settings.windowMax = True
        Else
            My.Settings.windowMax = False
            My.Settings.windowTop = Me.Top
            My.Settings.windowLeft = Me.Left
            My.Settings.windowHeight = Me.Height
            My.Settings.windowWidth = Me.Width
        End If

    End Sub

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        DB = New classDB
        AddHandler DB.Progress, AddressOf DB_Progress

        If My.Settings.db_init = False Then
            'Open settings
            MsgBox("Please setup db connection first!")

            Dim frm As New frmSettings
            frm.ShowDialog()
            Do Until My.Settings.db_init = True
                Dim ret = MsgBox("You have to have a working database to be able to use this application!" & vbNewLine & vbNewLine & _
                    "Do you wish to try again?", vbYesNo)
                If ret = MsgBoxResult.No Then
                    Application.Exit()
                End If
                frm.ShowDialog()
            Loop
        End If

        ListView1.Columns.Clear()
        If My.Settings.mnuCollumns = "" Then
            For Each x As ToolStripMenuItem In mnuCollumn.DropDownItems
                x.Checked = True
                ListView1.Columns.Add(x.Text)
            Next
        Else
            Dim cTest() As String = My.Settings.mnuCollumns.Split(",")
            For Each x As ToolStripMenuItem In mnuCollumn.DropDownItems
                If InArray(x.Text, cTest) Then
                    x.Checked = True
                    ListView1.Columns.Add(x.Text)
                End If
            Next
        End If
        If My.Settings.mnuCollumns_width <> "" Then
            Dim sSettings() As String = My.Settings.mnuCollumns_width.Split(",")

            For Each x As System.Windows.Forms.ColumnHeader In ListView1.Columns
                x.Width = getWidth(x.Text, sSettings)
            Next
        End If


        If My.Settings.windowMax Then Me.WindowState = FormWindowState.Maximized
        If My.Settings.windowHeight > 0 Then Me.Height = My.Settings.windowHeight
        If My.Settings.windowWidth > 0 Then Me.Width = My.Settings.windowWidth
        If My.Settings.windowTop > 0 Then Me.Top = My.Settings.windowTop
        If My.Settings.windowLeft > 0 Then Me.Left = My.Settings.windowLeft

        With My.Settings
            DB.confMySQL_Database = .db_db
            DB.confMySQL_Hostname = .db_server
            DB.confMySQL_Password = .db_pass
            DB.confMySQL_Port = .db_port
            DB.confMySQL_Username = .db_user
        End With
        ConnectToolStripMenuItem.Checked = My.Settings.db_offline
        If My.Settings.db_offline Then
            Timer1.Enabled = False
            lblStatus.Text = "Offline"
        Else
            DB.Connect()
            RefreshList()
            Timer1.Enabled = True
        End If
    End Sub

    Public Function InArray(ByVal strSearch As String, ByRef strArray() As String) As Boolean
        Dim ret As Boolean = False
        strSearch = LCase(strSearch)
        For Each Str As String In strArray
            If LCase(Str) = strSearch Then
                ret = True
                Exit For
            End If
        Next
        Return ret
    End Function

    Public Function getWidth(ByRef strSearch As String, ByVal sSettings() As String) As Integer
        Dim ret As Integer = 60

        For Each StrTemp As String In sSettings
            If StrTemp.Trim <> "" Then
                Dim setting As String = StrTemp.Substring(0, InStr(StrTemp, "=") - 1)
                If setting = strSearch Then
                    Dim strBuffer As String = StrTemp.Substring(InStr(StrTemp, "="))
                    ret = Val(strBuffer)
                    Exit For
                End If
            End If
        Next

        Return ret
    End Function

    Public Sub RefreshList()
        lblStatus.Text = "Downloading trades..."
        DB.UpdateCollections(colTrades)
        'get trades...
        ListView1.Items.Clear()
        pProgress.Value = 90
        For Each x As classTrades In colTrades
            ListView1.Items.Add(x.getLW)
            If Not colSymbols.Contains(x.Symbol) Then colSymbols.Add(x.Symbol, x.Symbol)
            If Not colSystems.Contains(x.System) Then colSystems.Add(x.System, x.System)
        Next
        pProgress.Value = 100
        lblStatus.Text = "Connected"
    End Sub

    Public Sub DB_Progress(ByRef iPercentage)
        pProgress.Value = iPercentage
    End Sub

    Private Sub SettingsToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SettingsToolStripMenuItem.Click
        Dim frm As New frmSettings
        frm.ShowDialog()
    End Sub

    Private Sub ReconnectToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ReconnectToolStripMenuItem.Click
        Dim c As Cursor = Me.Cursor
        Me.Cursor = Cursors.WaitCursor
        If Not DB.State = ConnectionState.Closed Then DB.Close()
        DB.Connect()
        RefreshList()
        Me.Cursor = c
    End Sub

    Private Sub ExitToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExitToolStripMenuItem.Click
        Application.Exit()
    End Sub

    Private Sub ListView1_ColumnClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.ColumnClickEventArgs) Handles ListView1.ColumnClick
        ' Determine whether the column is the same as the last column clicked.
        If e.Column <> sortColumn Then
            ' Set the sort column to the new column.
            sortColumn = e.Column
            ' Set the sort order to ascending by default.
            ListView1.Sorting = SortOrder.Ascending
        Else
            ' Determine what the last sort order was and change it.
            If ListView1.Sorting = SortOrder.Ascending Then
                ListView1.Sorting = SortOrder.Descending
            Else
                ListView1.Sorting = SortOrder.Ascending
            End If
        End If
        ' Call the sort method to manually sort.
        ListView1.Sort()
        ' Set the ListViewItemSorter property to a new ListViewItemComparer
        ' object.
        ListView1.ListViewItemSorter = New ListViewItemComparer(e.Column, ListView1.Sorting)

    End Sub

    Private Sub ToolStripButton2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButton2.Click
        Dim frm As New vbTrade
        Dim c As New classTrades
        frm.Tag = c
        frm.ShowDialog()
        Dim cur As Cursor = Me.Cursor
        Me.Cursor = Cursors.WaitCursor
        If Not ConnectToolStripMenuItem.Checked Then
            If DB.State = ConnectionState.Open Then
                If DB.UpdateTrade(c) Then
                Else
                    MsgBox("Connection to database lost!" & vbNewLine & "Do not close the application before connection is restored to save trades!")
                    colUnsavedTrades.Push(c)
                End If
            Else
                MsgBox("Connection to database lost!" & vbNewLine & "Do not close the application before connection is restored to save trades!")
                colUnsavedTrades.Push(c)
            End If
        Else
            c.Online = False
            colUnsavedTrades.Push(c)
        End If
        Me.Cursor = cur
        If Not colSymbols.Contains(c.Symbol) Then colSymbols.Add(c.Symbol, c.Symbol)
        If Not colSystems.Contains(c.System) Then colSystems.Add(c.System, c.System)
        ListView1.Items.Add(c.getLW)
    End Sub

    Public Sub SaveUnsavedItems()
        If colUnsavedTrades.Count > 0 Then
            Dim strOldStatus As String = lblStatus.Text
            lblStatus.Text = "Saving items"
            DB.Connect()
            If DB.State = ConnectionState.Open Then
                Dim x As classTrades
                Do Until colUnsavedTrades.Count = 0
                    x = colUnsavedTrades.Pop
                    If DB.UpdateTrade(x) Then
                        ListView1.Items.Add(x.getLW)
                        colTrades.Add(x, CStr(x.ID))
                    Else
                        strOldStatus = "Disconnected!"
                        Exit Do
                    End If
                Loop
                lblStatus.Text = strOldStatus
            Else
                lblStatus.Text = "Disconnected!"
                lblStatus.ForeColor = Color.Red
            End If
        End If
    End Sub

    Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
        If DB.State = ConnectionState.Open And DB.conn.Ping() Then
            lblStatus.Text = "Connected"
            lblStatus.ForeColor = Color.Black
            Timer1.Interval = 1000
            SaveUnsavedItems()
            Timer1.Enabled = True
        Else
            lblStatus.Text = "Disconnected!"
            lblStatus.ForeColor = Color.Red
            Timer1.Enabled = False

            Try
                SaveUnsavedItems()

            Catch ex As MySql.Data.MySqlClient.MySqlException
                If ex.Number <> 1042 Then
                    MsgBox(ex.Message)
                End If
            End Try
            If DB.State = ConnectionState.Open Then
                lblStatus.Text = "Connected"
                lblStatus.ForeColor = Color.Black
                Timer1.Interval = 1000
            Else
                lblStatus.Text = "Disconnected!"
                lblStatus.ForeColor = Color.Red
                Timer1.Interval = 10000
            End If
            Timer1.Enabled = True
        End If
    End Sub

    Private Sub ConnectToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ConnectToolStripMenuItem.Click
        If ConnectToolStripMenuItem.Checked Then
            ConnectToolStripMenuItem.Checked = Not ConnectToolStripMenuItem.Checked
            'ONLINE
            Timer1.Enabled = True
            lblStatus.Text = "Connected"
            lblStatus.ForeColor = Color.Black
            Timer1.Interval = 1000
        Else
            ConnectToolStripMenuItem.Checked = Not ConnectToolStripMenuItem.Checked
            'OFFLINE
            lblStatus.Text = "Offline"
            lblStatus.ForeColor = Color.Black
            Timer1.Enabled = False
            Timer1.Interval = 10000
            If DB.State <> ConnectionState.Closed Then
                DB.Close()
            End If
        End If
        My.Settings.db_offline = ConnectToolStripMenuItem.Checked
    End Sub

    Private Sub ListView1_MouseDoubleClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles ListView1.MouseDoubleClick
        If ListView1.SelectedItems.Count = 1 Then
            Dim lw As ListViewItem = ListView1.SelectedItems.Item(0)
            Dim C As classTrades = CType(lw.Tag, classTrades)
            If C.Online Then
                ListView1.Items.Remove(lw)
                Dim frm As New vbTrade
                frm.Tag = C
                frm.ShowDialog()
                Dim cur As Cursor = Me.Cursor
                Me.Cursor = Cursors.WaitCursor
                C = CType(frm.Tag, classTrades)
                If colTrades.Contains(CStr(C.ID)) Then
                    colTrades.Remove(CStr(C.ID))
                End If
                If Not ConnectToolStripMenuItem.Checked Then
                    If DB.UpdateTrade(C) Then
                        colTrades.Add(CType(frm.Tag, classTrades), CStr(CType(frm.Tag, classTrades).ID))
                        lw = C.getLW
                    Else
                        C.Online = False
                        colUnsavedTrades.Push(C)
                        lblStatus.Text = "Disconnected!"
                        lblStatus.ForeColor = Color.Red
                        lw = C.getLW
                    End If
                    ListView1.Items.Add(lw)
                Else
                    C.Online = False
                    colUnsavedTrades.Push(C)
                    lw = C.getLW
                End If
                Me.Cursor = cur
            Else
                MsgBox("This item is not saved online, and can therefore not be edited!")
            End If
        End If
    End Sub

    Private Sub mnuCollumns_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuID.Click, mnuTP.Click, mnuSymbol.Click, mnuStatus.Click, mnuSL.Click, mnuResults.Click, mnuPriceEntered.Click, mnuPriceClose.Click, mnuOpen.Click, mnuDirection.Click, mnuComment.Click, mnuClose.Click, RatioToolStripMenuItem.Click, LotSizeToolStripMenuItem.Click, SystemToolStripMenuItem.Click
        CType(sender, ToolStripMenuItem).Checked = Not CType(sender, ToolStripMenuItem).Checked
        ListView1.Columns.Clear()
        ListView1.Items.Clear()
        Dim strSetting As String = ""
        Dim strColWidrth() As String = My.Settings.mnuCollumns_width.Split(",")
        For Each x As ToolStripMenuItem In mnuCollumn.DropDownItems
            If x.Checked Then
                Dim col As System.Windows.Forms.ColumnHeader
                col = ListView1.Columns.Add(x.Text)
                col.Width = getWidth(x.Text, strColWidrth)
                strSetting = x.Text & "," & strSetting
            End If
        Next
        My.Settings.mnuCollumns = strSetting
        My.Settings.mnuCollumns_width = Join(strColWidrth, ",")
        For Each x As classTrades In colTrades
            ListView1.Items.Add(x.getLW)
        Next
        For Each x As classTrades In colUnsavedTrades
            ListView1.Items.Add(x.getLW)
        Next
    End Sub

    Private Sub ToolStripButton1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButton1.Click
        Dim ret = MsgBox("Are you sure you want to delete this item?", vbYesNo)
        If ret = MsgBoxResult.Yes Then
            If DB.State = ConnectionState.Open Then
                If ListView1.SelectedItems.Count = 1 Then
                    Dim lw As ListViewItem = ListView1.SelectedItems.Item(0)
                    Dim C As classTrades = CType(lw.Tag, classTrades)

                    If C.Online Then
                        DB.DeleteTrade(C)
                        ListView1.Items.Remove(lw)
                        colTrades.Remove(CStr(C.ID))
                    Else
                        MsgBox("The item has to be online to be able to remove it!")
                    End If
                End If
            Else
                MsgBox("You have to be online to delete online items!")
            End If
        End If
    End Sub

    Private Sub ListView1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ListView1.SelectedIndexChanged

    End Sub
End Class

'Visual Basic 
' Implements the manual sorting of items by column.
Class ListViewItemComparer
    Implements IComparer
    Private col As Integer
    Private order As SortOrder

    Public Sub New()
        col = 0
        order = SortOrder.Ascending
    End Sub

    Public Sub New(ByVal column As Integer, ByVal order As SortOrder)
        col = column
        Me.order = order
    End Sub

    'Visual Basic 
    Public Function Compare(ByVal x As Object, ByVal y As Object) As Integer Implements System.Collections.IComparer.Compare
        Dim returnVal As Integer
        ' Determine whether the type being compared is a date type.
        Try
            ' Parse the two objects passed as a parameter as a DateTime.
            Dim firstDate As System.DateTime = DateTime.Parse(CType(x,  _
                                    ListViewItem).SubItems(col).Text)
            Dim secondDate As System.DateTime = DateTime.Parse(CType(y,  _
                                      ListViewItem).SubItems(col).Text)
            ' Compare the two dates.
            returnVal = DateTime.Compare(firstDate, secondDate)
            ' If neither compared object has a valid date format, 
            ' compare as a string.
        Catch
            ' Compare the two items as a string.
            returnVal = [String].Compare(CType(x,  _
                              ListViewItem).SubItems(col).Text, CType(y, ListViewItem).SubItems(col).Text)
        End Try

        ' Determine whether the sort order is descending.
        If order = SortOrder.Descending Then
            ' Invert the value returned by String.Compare.
            returnVal *= -1
        End If
        Return returnVal
    End Function
End Class